﻿

#region Using Statements

using UnityEngine;
using System.Collections.Generic;

#endregion


/// <summary>
/// 
/// </summary>
public class BufferedVal<T>
    where T : System.IComparable
{

    #region Members

    /// <summary>
    /// 
    /// </summary>
    protected T[] buf { get; set; }


    /// <summary>
    /// 
    /// </summary>
    public virtual T val
    {
        get { return buf[0]; }
        set { HardSet(value); }
    }

    #endregion


    #region Init

    /// <summary>
    /// 
    /// </summary>
    /// <param name="bufLen"></param>
    public BufferedVal(int bufLen)
    {
        buf = new T[bufLen];
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="bufLen"></param>
    /// <param name="v"></param>
    public BufferedVal(int bufLen, T v)
    {
        buf = new T[bufLen];
        val = v;
    }

    #endregion


    #region Setters

    /// <summary>
    /// 
    /// </summary>
    /// <param name="v"></param>
    public virtual void SoftSet(T v)
    {
        int i = buf.Length - 1;
        for (; i >= 0 && buf[i].CompareTo(v) == 0; --i) { }
        if (i >= 0)
            buf[i] = v;
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="v"></param>
    public virtual void HardSet(T v)
    {
        for (int i = 0; i < buf.Length; i++) 
            buf[i] = v;
    }

    #endregion


    #region Reinforce

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public bool Reinforce()
    {
        T c = buf[0];
        T v = buf[buf.Length - 1];

        for (int i = buf.Length - 2; i >= 0; --i)
            if (buf[i].CompareTo(v) != 0)
            {
                buf[i] = v;
                break;
            }

        return buf[0].CompareTo(c) != 0;
    }

    #endregion

}